<template>
  <div class="order-management">
    <el-card>
      <!-- <template #header>
        <div class="card-header">
          <span>订单管理</span>
          
          <el-input
            v-model="searchQuery"
            placeholder="输入订单号/用户名搜索"
            style="width: 300px"
            clearable
            @clear="handleSearch"
            @keyup.enter="handleSearch"
          >
            <template #append>
              <el-button :icon="Search" @click="handleSearch" />
            </template>
          </el-input>
        </div>
      </template> -->
      <template #header>
        <div class="card-header">
          <span>订单管理</span>
          <div class="header-actions">
            <el-input
              v-model="searchQuery"
              placeholder="输入订单号/用户名搜索"
              style="width: 300px"
              clearable
              @clear="handleSearch"
              @keyup.enter="handleSearch"
            >
              <template #append>
                <el-button :icon="Search" @click="handleSearch" />
              </template>
            </el-input>
          </div>
        </div>
      </template>


      <el-table
        :data="orderList"
        v-loading="loading"
        border
        style="width: 100%"
        
      >
        <el-table-column prop="orderNumber" label="订单编号" width="220" />
        <el-table-column label="宠物信息" width="180">
          <template #default="{ row }">
            <div class="pet-info">
              <el-image
                :src="row.animalInfo.imageUrl"
                :preview-src-list="[row.animalInfo.imageUrl]"
                fit="cover"
                style="width: 40px; height: 40px; border-radius: 4px"
              />
              <span style="margin-left: 10px">{{ row.animalInfo.name }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="buyerInfo.userName" label="买家" width="120" />
        <el-table-column prop="finalPrice" label="金额" width="120">
          <template #default="{ row }">
            ¥{{ row.finalPrice.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="120">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="payTime" label="支付时间" width="180" />
        <el-table-column label="操作" width="120">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              @click.stop="showOrderDetail(row.id)"
            >
              详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        :current-page.sync="currentPage"
        :page-size.sync="pageSize"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="fetchOrders"
        @current-change="fetchOrders"
        />
    </el-card>

    <!-- 订单详情对话框 -->
    <!-- <el-dialog v-model="detailVisible" title="订单详情" width="50%">
      <order-detail v-if="detailVisible" :order-id="currentOrderId" />
    </el-dialog> -->
    <!-- 订单详情对话框 -->
    <el-dialog 
      v-model="detailVisible" 
      title="订单详情" 
      width="50%"
      :close-on-click-modal="false"
    >
      <div v-if="currentOrder" class="order-detail-content">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="订单编号">
            {{ currentOrder.orderNumber || '无' }}
          </el-descriptions-item>
          <el-descriptions-item label="订单状态">
            <el-tag :type="getStatusType(currentOrder.status)">
              {{ getStatusText(currentOrder.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="支付金额">
            ¥{{ currentOrder.finalPrice?.toFixed(2) || '0.00' }}
          </el-descriptions-item>
          <el-descriptions-item label="支付时间">
            {{ formatTime(currentOrder.payTime) }}
          </el-descriptions-item>
        </el-descriptions>

        <el-divider />

        <h3>宠物信息</h3>
        <div class="pet-info">
          <el-image
            :src="currentOrder.animalInfo?.imageUrl"
            :preview-src-list="[currentOrder.animalInfo?.imageUrl]"
            fit="cover"
            style="width: 100px; height: 100px; border-radius: 4px"
          />
          <div class="pet-detail">
            <p><strong>宠物ID:</strong> {{ currentOrder.animalInfo?.id || '无' }}</p>
            <p><strong>宠物名称:</strong> {{ currentOrder.animalInfo?.name || '无' }}</p>
          </div>
        </div>

        <el-divider />

        <h3>买家信息</h3>
        <div class="buyer-info">
          <p><strong>用户ID:</strong> {{ currentOrder.buyerInfo?.id || '无' }}</p>
          <p><strong>用户名:</strong> {{ currentOrder.buyerInfo?.userName || '无' }}</p>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { Search } from '@element-plus/icons-vue'
// import { getOrderList, getOrderDetail } from '../../api/order'
// import { OrderDetail } from './OrderDetail.vue'
import { useRouter } from 'vue-router'
import { getOrderList,getOrderListpage } from '../../api/order'
import { formatTime } from '../../utils/date'
import { ElMessage } from 'element-plus'

const searchQuery = ref('')
const detailVisible = ref(false)
const currentOrder = ref(null)
const router = useRouter()
const orderList = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const loading = ref(false)

// 获取订单列表
const fetchOrders = async () => {
  try {
    loading.value = true;
    const params = {
      page: currentPage.value,
      size: pageSize.value,
      keyword: searchQuery.value
    };
    // 调用后端接口
    const res = await getOrderListpage(params);
    // 调试日志
    console.log('API响应数据:', {
      data: res?.data,
      records: res?.records,
      total: res?.total
    });

    // 检查res.records是否存在
    if (res && res.records) {
      orderList.value = res.records; // 使用res.records作为订单列表
      total.value = res.total; // 使用res.total作为总记录数
    } else {
      // 如果res.records不存在，可能是后端返回的数据结构有问题
      console.warn('后端返回的数据结构不符合预期:', res);
      orderList.value = []; // 设置订单列表为空
      total.value = 0; // 设置总记录数为0
    }
  } catch (error) {
    console.error('获取订单列表失败:', error);
    ElMessage.error('获取订单列表失败');
  } finally {
    loading.value = false;
  }
};

// 搜索订单
const handleSearch = () => {
  currentPage.value = 1
  fetchOrders()
}

// 订单状态映射
const getStatusText = (status) => {
  const statusMap = {
    0: '待支付',
    1: '已完成',
    2: '已取消',
  }
  return statusMap[status] || '未知状态'
}

const getStatusType = (status) => {
  const typeMap = {
    0: 'warning',
    1: 'success',
    2: 'info',
    3: 'danger'
  }
  return typeMap[status] || ''
}

onMounted(() => {
  fetchOrders()
})
</script>

<style scoped>
.order-management {
  padding: 20px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.pet-info {
  display: flex;
  align-items: center;
}
.el-table {
  margin-top: 20px;
}
.el-pagination {
  margin-top: 20px;
  justify-content: flex-end;
}
</style>